package com.qf.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.qf.common.R;
import com.qf.mapper.StudentMapper;
import com.qf.mapper.impl.StudentMapperImpl;
import com.qf.pojo.Student;
import com.qf.pojo.Teacher;
import com.qf.pojo.User;
import com.qf.service.StudentService;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import com.qf.servlet.BaseServlet;
import com.qf.utils.DBUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;

@WebServlet("/user")
public class UserController extends BaseServlet {

    private UserService userService = new UserServiceImpl();
    private StudentMapper studentMapper   = new StudentMapperImpl();

    public void doDrawCode(HttpServletRequest request, HttpServletResponse response) {
        userService.drawCode(request, response);
    }

    public void doLogin(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
         userService.login(request, response);
    }

    public void doLoginOut(HttpServletRequest request, HttpServletResponse response) throws IOException {
        userService.loginOut(request, response);
        response.sendRedirect("welcome.html");
    }

    public void doResetPassword(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         userService.resetPassword(request, response);

    }

    public void getUser(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException {
        String username = request.getParameter("username");
        Object role = request.getParameter("role");
        User user = new User();
        if("student".equals(role)){
             user = DBUtils.commonQueryObj(Student.class,  "select * from student where username =?", username);
        }else if("teacher".equals(role)){
            user = DBUtils.commonQueryObj(Teacher.class,  "select * from teacher where username =?", username);
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("role", role);
        if(user != null){
            response.getWriter().write(JSONArray.toJSONString(R.success("获取用户信息成功", map)));
        }else{
            response.getWriter().write(JSON.toJSONString(R.fail("获取用户信息失败")));
        }
    }
}